package com.hui.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 配置被允许访问此认证服务器的客户端信息
     * 1.内存方式
     * 2.数据库方式
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //内存
        clients.inMemory()
                .withClient("clientapp")
                .secret(passwordEncoder.encode("123456"))
                .accessTokenValiditySeconds(3600)
                .redirectUris("http://www.baidu.com")
                .authorizedGrantTypes("password", "authorization_code", "client_credentials")
                .scopes("all")
                .resourceIds("oauth-server-api")
                .and()
                .withClient("clientapp2")
                .secret(passwordEncoder.encode("123456"))
                .accessTokenValiditySeconds(3600)
                .redirectUris("http://www.baidu.com")
                .authorizedGrantTypes("password", "authorization_code", "client_credentials")
                .scopes("Admin", "SuperAdmin")
                .redirectUris("http://www.baidu.com")
                .resourceIds("oauth-server-api2")
        ;
    }

    /**
     * 参数名称叫授权服务器端点配置器
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        // password 要这个 AuthenticationManager 实例
        endpoints.authenticationManager(authenticationManager);
    }


    /**
     * 允许ClientSecret明文方式保存并且可以通过表单提交
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.checkTokenAccess("permitAll()").allowFormAuthenticationForClients();
    }


}

